const vscode = require("vscode");

// 模拟 Fpstream 对象及其方法
const fpstreamMethods = require("./fpstreamMethods.js");

/**
 * 提供补全项
 * @param {vscode.TextDocument} document - 当前文档
 * @param {vscode.Position} position - 光标位置
 * @param {vscode.CancellationToken} token - 用于取消操作的标记
 * @param {vscode.CompletionContext} context - 补全上下文，可以提供触发补全的原因
 */
function provideCompletionItems(document, position, token, context) {
  const linePrefix = document
    .lineAt(position)
    .text.substr(0, position.character);

  // 匹配 Fpstream.后跟方法名的模式
  const match = linePrefix.match(/Fpstream\.([^\(\s]*)/);
  // console.log("Your match == ", match);
  if (match) {
    const currentMatchArr = match[0].split(".");
    let suggestions = [];
    // 二级方法
    if (currentMatchArr.length === 2) {
      suggestions = Object.keys(fpstreamMethods)
        .filter((property) => property.startsWith(currentMatchArr[1]))
        .map((property) => {
          const item = new vscode.CompletionItem(property);
          item.kind = vscode.CompletionItemKind.Function;

          if (typeof fpstreamMethods[property] === "string") {
            item.insertText = new vscode.SnippetString(
              `${property}${fpstreamMethods[property]}`
            );
          } else {
            item.insertText = new vscode.SnippetString(`${property}`);
          }
          item.sortText = "0_" + property;
          item.detail = "from fqbbmnn =。=";
          return item;
        });
    } else if (currentMatchArr.length === 3) {
      // 三级方法
      suggestions = Object.keys(fpstreamMethods[currentMatchArr[1]])
        .filter((property) => property.startsWith(currentMatchArr[2]))
        .map((property) => {
          const item = new vscode.CompletionItem(property);
          item.kind = vscode.CompletionItemKind.Function;
          item.insertText = new vscode.SnippetString(
            `${property}${fpstreamMethods[currentMatchArr[1]][property]}`
          );
          item.sortText = "0_" + property;
          item.detail = "from fqbbmnn =。=";
          return item;
        });
    }

    return new vscode.CompletionList(suggestions, true);
  }
  const rootMatch = linePrefix.match(/F/);
  if (rootMatch) {
    const item = new vscode.CompletionItem("Fpstream");
    item.kind = vscode.CompletionItemKind.Constructor;
    item.insertText = new vscode.SnippetString("Fpstream");
    item.sortText = "AAAAA_Fpstream";
    item.detail = "from fqbbmnn =。=";
    return new vscode.CompletionList([item], true);
  }
  return [];
}

/**
 * 插件激活时调用
 * @param {vscode.ExtensionContext} context - VSCode上下文
 */
function activate(context) {
  console.log("Your Fpstream extension is active!");

  const provider = vscode.languages.registerCompletionItemProvider(
    ["javascript", "typescript", "vue"],
    {
      provideCompletionItems,
    },
    "." // 触发补全的字符
  );

  context.subscriptions.push(provider);
}

/**
 * 插件停用时调用
 */
function deactivate() {}

module.exports = {
  activate,
  deactivate,
};
